/**
 * 
 */
package com.pmsco.pms.core.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.pmsco.pms.core.dao.PmsPermissionRoleDao;
import com.pmsco.pms.core.domain.PmsPermission;
import com.pmsco.pms.core.domain.PmsPermissionRole;
import com.pmsco.pms.core.domain.PmsRole;

/**
 * @author Tran Thanh Long
 *
 */
public class PmsPermissionRoleDaoImpl extends HibernateDaoSupport implements PmsPermissionRoleDao {

	public void saveOrUpdatePmsPermissionRole(PmsPermissionRole pmsPermissionRole) {
		getHibernateTemplate().merge(pmsPermissionRole);
		getHibernateTemplate().flush();
	}

	public List<PmsPermissionRole> listPmsPermissionByRole(PmsPermissionRole searchTemplate) {
		List<PmsPermissionRole> ret = new ArrayList<PmsPermissionRole>();
		Criteria crit = this.getSession().createCriteria(PmsPermissionRole.class);
		crit.createAlias(PmsPermissionRole.roleObj, PmsPermissionRole.roleObj);
        crit.createAlias(PmsPermissionRole.permissionObj, PmsPermissionRole.permissionObj);
        crit.add(Restrictions.eq(PmsPermissionRole.roleObj + "." + PmsRole.idField, searchTemplate.getRole().getId()));
        crit.addOrder(Order.asc(PmsPermissionRole.permissionObj + "." + PmsPermission.permissionField));
		ret = crit.list();
		return ret;
	}

	public List<PmsPermissionRole> loadPmsPermissionRoleByPermissionId(Long permissionId) {
		List<PmsPermissionRole> ret = new ArrayList<PmsPermissionRole>();
		Criteria crit = this.getSession().createCriteria(PmsPermissionRole.class);
        crit.createAlias(PmsPermissionRole.permissionObj, PmsPermissionRole.permissionObj);
        crit.add(Restrictions.eq(PmsPermissionRole.permissionObj + "." + PmsPermission.idField, permissionId));
		ret = crit.list();
		return ret;
	}
	
	public List<PmsPermissionRole> loadPmsPermissionRoleByName(String name) {
		List<PmsPermissionRole> ret = new ArrayList<PmsPermissionRole>();
		Criteria crit = this.getSession().createCriteria(PmsPermissionRole.class);
        crit.createAlias(PmsPermissionRole.permissionObj, PmsPermissionRole.permissionObj);
        crit.add(Restrictions.eq(PmsPermissionRole.permissionObj + "." + PmsPermission.permissionField, name));
		ret = crit.list();
		return ret;
	}

	public PmsPermissionRole loadPmsPermissionRole(PmsPermissionRole searchTemplate) {
		PmsPermissionRole ret = null;
		List<PmsPermissionRole> temp = new ArrayList<PmsPermissionRole>();
		temp = getHibernateTemplate().findByExample(searchTemplate);
		if(temp != null && temp.size() == 1)
			ret = temp.get(0);
		return ret;
	}

	public void deletePmsPermissionRole(PmsPermissionRole pmsPermissionRole) {
		getHibernateTemplate().delete(pmsPermissionRole);
		getHibernateTemplate().flush();
	}

}
